package com.chuangjiangx.member.basic.web.controller;

import com.chuangjiangx.commons.sms.SMSUtils;
import com.chuangjiangx.member.basic.web.redis.SessionService;
import com.chuangjiangx.member.basic.web.request.LoginRequest;
import com.chuangjiangx.member.basic.ddd.query.MemberQuery;
import com.chuangjiangx.member.basic.ddd.query.dto.MemberDTO;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Objects;

/**
 * 用于获取会员信息
 * Created by YangKuo on 2017/11/14.
 */
public class BaseController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    protected SessionService loginService;

    @Autowired
    protected MemberQuery memberQuery;


    protected boolean isValidLogin(MbrUserContext userContext, Long urlMerchantId){
        Long memberId = userContext.getMemberId();
        if(null != memberId){
            //session中已经有了手机号码
            MemberDTO memberDTO = memberQuery.queryByMemberId(memberId);
            if(memberDTO == null || StringUtils.isBlank(memberDTO.getMobile())){
                return false;
            }
            if(Objects.equals(urlMerchantId,memberDTO.getMerchantId())){
                //用户已经登录
                userContext.setName(memberDTO.getName());
                userContext.setHeadimgurl(memberDTO.getHeadimgurl());
                userContext.setFaceId(memberDTO.getFaceId());
                return true;
                //else session中的用户可能已经被删除并且重新注册了
            }
            //else Session中记录的商户与实际的商户不一致
            //else  session中的手机号码可能已经被删除
        }
        return false;
    }

    protected boolean isValidLogin(){
        MbrUserContext context = loginService.currentUserContext();
        if(null != context.getMerchantId()){
            return isValidLogin(context,context.getMerchantId());
        }
        return false;
    }

    /**
     * 验证验证码
     *
     * @param request
     * @return
     */
    protected boolean checkVerifyCode(LoginRequest request) throws Exception {

        // 校验短信验证码是否正确
        if (SMSUtils.codeCheck(request.getMobile(), request.getVerifyCode(), redisTemplate)) {
            //验证通过，清除redis中code
            SMSUtils.cleanCode(redisTemplate, request.getVerifyCode());
            return true;
        } else {
            return false;
        }
    }

}
